package com.lonewalker.sparrow.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author lonewalker
 */
@Slf4j
public class ConvertUtil {
    public ConvertUtil() {
    }

    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        } else {
            T targetObject = null;

            try {
                targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
            } catch (Exception exception) {
                log.error("convert error ", exception);
            }

            return targetObject;
        }
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        } else {
            List<T> targetList = new ArrayList<>(sourceList.size());
            try {
                for (Object source : sourceList) {
                    T targetObject = target.newInstance();
                    BeanUtils.copyProperties(source, targetObject);
                    targetList.add(targetObject);
                }
            } catch (Exception exception) {
                log.error("convert error ", exception);
            }
            return targetList;
        }
    }
}
